
<template>
	<div class="mobileMonitorInput">
    <div class="stepsBox" style="display:none">
      <el-steps :active="inputActive" finish-status="success" align-center>
        <el-step title="填写线路信息"></el-step>
        <el-step title="填写点位信息"></el-step>
        <el-step title="完 成"></el-step>
      </el-steps>
    </div>
    <div class="inputContent" v-loading="inputLoading">
      <div class="lineInfoBox" v-show="inputActive === 0">
        <div class="title">填写线路信息</div>
        <el-form ref="lineForm" :rules="inputLineFormRules" :model="inputLineForm" size="mini" label-width="80px"  style="width: 60%;">
          <el-row>
            <el-col :span="11">
              <el-form-item label="监测时间" prop="name">
                <el-date-picker 
                  type="date" 
                  placeholder="选择监测时间"
                  v-model="inputLineForm.name" 
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="1">
              <el-form-item label="车辆编号" prop="vehicleId">
                <el-select v-model="inputLineForm.vehicleId" placeholder="请选择车辆编号" style="width: 100%">
                  <el-option v-for="item of vehicleNumList" :key="item.id" :label="item.name" :value="item.name" ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="监测人员" prop="person">
                <el-input v-model="inputLineForm.person" placeholder="选择监测人员" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="1">
              <el-form-item label="监测类型" prop="type">
                <el-radio-group v-model="inputLineForm.type" @change="lineTypeChange">
                  <el-radio label="0">定期</el-radio>
                  <el-radio label="1">不定期</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="任务编号">
                <el-input v-model="inputLineForm.taskId" placeholder="填写任务编号" :disabled="inputLineForm.type == 1"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="1">
              <el-form-item label="点位数量" prop="pointNumber" label-width="80px">
                <el-input v-model.number="inputLineForm.pointNumber" placeholder="填写点位数量"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-button class="greenBtn" size="mini" @click="stepOneSubmit('lineForm')">提交</el-button>
          </el-row>
        </el-form>
      </div>
      <div class="pointInfoBox" v-show="inputActive === 1">
        <div class="title">填写点位信息</div>
        <el-form ref="pointForm" class="pointForm" :rules="monitoringDataRules" :model="monitoringData" size="mini" label-width="90px">
          <el-row>
            <el-form-item label="路线编号" label-width="80px">
              <el-input v-model="monitoringData.routingName" disabled></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="监测时间" label-width="80px" prop="lastMonitor">
                <el-date-picker
                  v-model="monitoringData.lastMonitor"
                  type="datetime"
                  style="width: 100%"
                  value-format="yyyy-MM-dd hh:mm:ss"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="点位名称" prop="pollutantName">
                <!-- <el-input v-model="monitoringData.pollutantName" placeholder="点位名称"></el-input> -->
                <el-select v-model="monitoringData.pollutantName" placeholder="点位名称">
                  <p v-for="(item, index) of stationPollutant" :key="index">
                    <el-option :label="item.pollutantName" :value="item.pollutantName"></el-option>
                  </p>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="地理位置" label-width="80px" >
                <el-col :span="11">
                  <el-form-item label="" label-width="0px" prop="longitude">
                    <el-input v-model.number="monitoringData.longitude" type="number" placeholder="经度"></el-input>
                  </el-form-item>
                </el-col>
                <el-col class="line" :span="2">,</el-col>
                <el-col :span="11">
                  <el-form-item label="" label-width="0px" prop="latitude">
                    <el-input v-model.number="monitoringData.latitude" placeholder="纬度" type="number"></el-input>
                  </el-form-item>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="" label-width="15px" >
                <el-button @click="openMapDialog">打开地图</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="mhr"></div>
          <el-row>
            <el-form-item label="pH" style="width: 50%" label-width="80px" prop="ph">
              <el-input v-model.number="monitoringData.ph" placeholder="pH" type="number"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="CODcr" label-width="80px" prop="cod">
                <el-input v-model.number="monitoringData.cod" placeholder="COD值" type="number">
                  <template slot="append">mg / L</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总铜" prop="cuprum">
                <el-input v-model.number="monitoringData.cuprum" placeholder="总铜值" type="number">
                  <template slot="append">mg / L</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="氨氮" label-width="80px"  prop="ammoniaNitrogen">
                <el-input v-model.number="monitoringData.ammoniaNitrogen" placeholder="氨氮值" type="number">
                  <template slot="append">mg / L</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总镍" prop="nickel">
                <el-input v-model.number="monitoringData.nickel" placeholder="总镍值" type="number">
                  <template slot="append">mg / L</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="总磷" label-width="80px" prop="phosphorus">
                <el-input v-model.number="monitoringData.phosphorus" placeholder="总磷值" type="number">
                  <template slot="append">mg / L</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总铬" prop="chromium">
                <el-input v-model.number="monitoringData.chromium" placeholder="总铬值" type="number">
                  <template slot="append">mg / L</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="总氮" label-width="80px" prop="nitrogen">
                <el-input v-model.number="monitoringData.nitrogen" placeholder="总氮值" type="number">
                  <template slot="append">mg / L</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总氰化物" prop="prussiate">
                <el-input v-model.number="monitoringData.prussiate" placeholder="总氰化物值" type="number">
                  <template slot="append">mg / L</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="现场图片" label-width="80px">
              <el-upload
                ref="uploadPhoto"
                action=""
                :file-list="monitoringData.filesPhoto"
                list-type="picture"
                :limit="1"
                accept=".jpg,.png,.jpeg,.JPG,.PNG,.JPEG"
                :on-change="uploadChange"
                :on-exceed="uploadExceed" 
                :http-request="handleSubmit"
                :auto-upload="false"
              >
                <el-button>点击上传</el-button>
                <p slot="tip" class="uploadTips">照片格式为JPG，PNG</p>
              </el-upload>
            </el-form-item>
          </el-row>
          <el-form-item label-width="0px" style="margin-top: 30px;">
            <el-button class="greenBtn" size="mini" @click="stepTwoSubmit('pointForm')">提交</el-button>
            <el-button size="mini" @click="backOverview">回到列表</el-button>
          </el-form-item>
        </el-form>
        
      </div>
      <div class="successBox" v-show="inputActive > 1">
        <div class="success">
          <i class="el-icon-check"></i>
        </div>
        <p class="successTips">提交成功, 2秒后跳转...</p>
      </div>
    </div>
    <el-dialog title="选择点位地址" width="80%" class="mapDialog" :visible.sync="mapDialogFlag" @close="destroyMap">
      <div id="map" class="map" v-loading="mapIsLoading" element-loading-background="rgba(249, 249, 249, 0.8)"></div>
    </el-dialog>
	</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import MapLoader from "../plugins/AMap.js";
import common from '@/plugins/common'
let mobMarker, mobGeocoder
export default {
  name: 'mobileMonitorInput',
  data () {
    let validateNegative = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('数值不能为负数'));
      }else {
        callback()
      }
    }
    return {
      msg: 'hello mobileMonitorInput!',
      inputLoading: false,
      inputActive: 0,

      map: null,
      mapDialogFlag: false,
      mapIsLoading: false,

      inputLineForm: {
        //线路信息
        name: '',
        vehicleId: '',
        person: '',
        type: '',
        taskId: '',
        pointNumber: '',
      },
      inputLineFormRules: {
        name: [
          { type: 'string', required: true, message: '请选择时间', trigger: 'change' }
        ],
        vehicleId: [
          { required: true, message: '请选择车辆编号', trigger: 'change' },
        ],
        person: [
          { required: true, message: '请输入监测人员', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择监测类型', trigger: 'change' }
        ],
        pointNumber: [
          { required: true, message: '请填写点位数量', trigger: 'blur' },
          { type: 'number', message: '点位数量必须为数字'}
        ],
      },
      monitoringFormData: {},
      monitoringData: {
        //点位信息
        routingName: '',
        ammoniaNitrogen: '',
        chromium: '',
        cod: '',
        cuprum: '',
        latitude: '',
        longitude: '',
        nickel: '',
        nitrogen: '',
        ph: '',
        phosphorus: '',
        prussiate: '',
        pollutantName: '',
        lastMonitor: '',
        photo: [],
      },
      monitoringDataRules: {
        ammoniaNitrogen: [
          { required: true, message: '请填写氨氮值', trigger: 'blur' },
          { validator: validateNegative, trigger: 'blur' },
          { type: 'number', message: '氨氮值必须为数字值'}
        ],
        chromium: [
          { required: true, message: '请填写总铬值', trigger: 'blur' },
          { validator: validateNegative, trigger: 'blur' },
          { type: 'number', message: '总铬值必须为数字值'}
        ],
        cod: [
          { required: true, message: '请填写COD值', trigger: 'blur' },
          { validator: validateNegative, trigger: 'blur' },
          { type: 'number', message: 'COD值必须为数字值'}
        ],
        cuprum: [
          { required: true, message: '请填写总铜值', trigger: 'blur' },
          { validator: validateNegative, trigger: 'blur' },
          { type: 'number', message: '总铜值必须为数字值'}
        ],
        nickel: [
          { required: true, message: '请填写总镍值', trigger: 'blur' },
          { validator: validateNegative, trigger: 'blur' },
          { type: 'number', message: '总镍值必须为数字值'}
        ],
        nitrogen: [
          { required: true, message: '请填写总氮值', trigger: 'blur' },
          { validator: validateNegative, trigger: 'blur' },
          { type: 'number', message: '总氮值必须为数字值'}
        ],
        ph: [
          { required: true, message: '请填写pH值', trigger: 'blur' },
          { validator: validateNegative, trigger: 'blur' },
          { type: 'number', message: 'pH值必须为数字值'}
        ],
        phosphorus: [
          { required: true, message: '请填写总磷值', trigger: 'blur' },
          { validator: validateNegative, trigger: 'blur' },
          { type: 'number', message: '总磷值必须为数字值'}
        ],
        prussiate: [
          { required: true, message: '请填写总氰化物值', trigger: 'blur' },
          { validator: validateNegative, trigger: 'blur' },
          { type: 'number', message: '总氰化物值必须为数字值'}
        ],

        latitude: [
          { required: true, message: '请填写纬度', trigger: 'blur' },
          { type: 'number', message: '纬度必须为数字值'}
        ],
        longitude: [
          { required: true, message: '请填写经度', trigger: 'blur' },
          { type: 'number', message: '经度必须为数字值'}
        ],
        pollutantName: [
          { required: true, message: '请填写点位名称', trigger: 'blur' },
        ],
        lastMonitor: [
          { type: 'string', required: true, message: '请选择监测时间', trigger: 'change' }
        ],
      }
		}
  },
  methods: {
    ...mapActions([
      'uploadMobileLine',
      'uploadMobileMonitor',
    ]),
    stepOneSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          /** 填写线路信息 */
          this.$confirm('是否确定线路信息填写正确?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '等等',
            type: 'warning'
          }).then(async () => {
            /** 提交线路信息 */
            this.inputLoading = true
            let result = await this.uploadMobileLine(this.inputLineForm)
            if(result.message !== 'success') {
              this.$notify.error({
                title: '错误',
                message: result.info
              });
              this.inputLoading = false
              return
            }
            this.monitoringData.routingName = result.routingName
            this.$message({
              type: 'success',
              message: '线路信息提交成功!'
            })
            //不进行下一步 录入点位信息
            // this.inputActive++
            // this.inputLoading = false

            //跳转到线路详情页
            this.$router.push('/mobileMonitor/overview/detail?name=' + result.routingName)
          }).catch(() => {})
        } else {
          return false;
        }
      })
    },
    stepTwoSubmit(formName) {
      let monitoringData = this.monitoringData
      let formdata = this.monitoringFormData
      var that = this
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if(monitoringData.photo.length != 1) {
            this.$notify({
              title: '警告',
              message: '图片至少上传一张',
              type: 'warning'
            });
            return;
          }
          this.inputLoading = true
          this.monitoringFormData = new FormData()
          this.monitoringFormData = common.formDataLoopAppen(this.monitoringFormData, monitoringData)
          this.$refs.uploadPhoto.submit()
          let result = await this.uploadMobileMonitor(this.monitoringFormData)
          if(result.message !== 'success') {
            this.$notify({
              title: '警告',
              message: result.info,
              type: 'warning'
            });
            this.inputLoading = false
            return;
          }
          this.inputLoading = false
          this.$confirm('点位数据提交成功, 是否继续新增点位?', '提示', {
            confirmButtonText: '继续新增',
            cancelButtonText: '不了谢谢',
            type: 'success'
          }).then(() => {
            this.$refs.pointForm.resetFields()
            this.monitoringData.photo = []
            this.$refs.uploadPhoto.clearFiles()
            mobMarker = mobGeocoder = null
          }).catch(() => {
            this.inputActive++
            setTimeout(_ => {
              this.$router.push('/mobileMonitor/overview')
            }, 1500)
          });
        } else {
          return false;
        }
      })
    },
    uploadChange(file, fileList){
			this.monitoringData.photo = fileList
    },
    uploadExceed(files, fileList) {
			this.$notify.warning({
				title: '警告',
				message: '最多上传1张图片',
			})
    },
    handleSubmit(response) {
			this.monitoringFormData.append('files', response.file)
    },
    lineTypeChange(val) {
      /** 监测类型改变 需要清空任务编号 */
      if(val === "1") {
        this.inputLineForm.taskId = ''
      }
    },
    backOverview() {
      /** 回到数据概览页面 */
      this.$router.push('/mobileMonitor/overview')
    },
    openMapDialog() {
      this.mapIsLoading = true
      this.createMap()
      this.mapDialogFlag = true
    },
    destroyMap() {
      this.map && this.map.destroy()
      // marker = null 
    },
    createMap() {
      let that = this
      MapLoader().then(
        AMap => {
          that.map = new AMap.Map('map', {
            center: [113.850234,22.673635],
            mapStyle: 'amap://styles/b23dc72b03be03f4dd932c413bc85c94',
            zoom: 11,
            zooms: [11, 18],
            resizeEnable: true
          })
          AMap.plugin(['AMap.ToolBar','AMap.Geocoder'],function(){//异步加载插件
            that.map.addControl(new AMap.Geocoder());
            that.map.addControl(new AMap.ToolBar());
          })
          that.map.on('click',(e) => {
            that.monitoringData.longitude = e.lnglat.lng
            that.monitoringData.latitude = e.lnglat.lat
            that.regeoCode()
          })
          if(mobMarker) {
            that.map.add(mobMarker)
            that.map.setFitView(mobMarker)
          }
          that.mapIsLoading = false
        },
        e => {
        }
      );
      
    },
    regeoCode() {
      let that = this
      let map = that.map
      let longitude = that.monitoringData.longitude
      let latitude = that.monitoringData.latitude
      if(!mobGeocoder){
        mobGeocoder = new AMap.Geocoder({
          radius: 1000
        });
      }
      if(!mobMarker){
        mobMarker = new AMap.Marker();
        map.add(mobMarker);
      }
      mobMarker.setPosition(new AMap.LngLat(longitude, latitude));
      mobGeocoder.getAddress(longitude + ',' + latitude, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          let address = result.regeocode.formattedAddress
        }else{
          this.$message.error('根据经纬度查询地址失败')
        }
      })
    },
  },
  computed: {
    ...mapGetters({
      vehicleNumList: 'getVehicleNumList',
      userInfo: 'getUserInfo',
      stationPollutant: 'getStationPollutant',
    })
  },
  created() {
    let routingName = this.$route.query.name
    let taskId = this.$route.query.taskId
    if(routingName) {
      this.inputActive = 1
      this.monitoringData.routingName = routingName
    }
    if(taskId) {
      this.inputLineForm.type = "0"
      this.inputLineForm.taskId = taskId
    }

    this.inputLineForm.person = this.userInfo.user.username
  },
  destroyed() {
    mobMarker = mobGeocoder = null
  },
}
</script>
<style scoped>
.mobileMonitorInput {
  min-height: 100%;
  background-color: #fff;
}
.mobileMonitorInput .title {
  position: relative;
  color: #666;
  line-height: 70px;
  font-size: 16px;
  margin-left: 15px;
}
.mobileMonitorInput .title::before {
  content: '';
  position: absolute;
  left: -15px;
  width: 4px;
  height: 20px;
  top: 25px;
  background-color: #2399ff;
}
.mobileMonitorInput .lineInfoBox,
.mobileMonitorInput .pointInfoBox {
  background: #fff;
  padding: 0 20px 35px 20px;
  margin-bottom: 15px;
}
.pointInfoBox .formAddBtn {
  margin-left: 15px;
}
.pointForm {
  width: 80%;
  margin-left: 15px;
  transition: .2s;
}
@media (min-width: 1600px) {
  .pointForm {
    width: 60%;
  }
}
.pointForm .line {
  text-align: center;
}
.pointForm .mhr {
  border-bottom: 1px dashed #d6d6d6;
  margin-bottom: 18px;
}
.pointForm .uploadTips {
  font-size: 12px;
  color: #666;
}
.stepsBox {
  background: #fff;
  padding: 20px;
  border-bottom: 1px solid #eee;
}
.inputContent {
  background: #fff;
  padding-top: 20px;
}
.successBox {
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.successBox .success {
  height: 50px;
  width: 50px;
  color: #59e388;
  border: 2px solid #59e388;
  border-radius: 50%;
  text-align: center;
  line-height: 50px;
  font-size: 35px;
}
.successBox .successTips {
  color: #9c9c9c;
  font-size: 14px;
  margin-top: 8px;
}
.mapDialog .map {
  width: 100%;
  height: 500px;
}
</style>